package com.yiwei.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Logger;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.yiwei.controller.third.RuiKangServiceBySqlServer;
import com.yiwei.controller.third.UserInfo;

public class AssistantHttpController {
	private Logger log = Logger.getLogger(AssistantHttpController.class.getName());
	private ConcurrentLinkedQueue<ImageFileInfoObject> imgIdQueue = null;
	private HttpServer httpServer;

	public AssistantHttpController() throws IOException {
		// 创建 http 服务器, 绑定本地 8080 端口
		httpServer = HttpServer.create(new InetSocketAddress(AssistantConfig.properties.getProperty("host"),
				Integer.parseInt(AssistantConfig.properties.getProperty("port"))), 0);

		// 创上下文监听, "/" 表示匹配所有 URI 请求
		httpServer.createContext("/", new HttpHandler() {
			@Override
			public void handle(HttpExchange httpExchange) throws IOException {
				// 设置跨域
				addCorsHeader(httpExchange);
				log.info("未匹配请求");
				log.info("addr: " + httpExchange.getRemoteAddress() + // 客户端IP地址
				"; protocol: " + httpExchange.getProtocol() + // 请求协议: HTTP/1.1
				"; method: " + httpExchange.getRequestMethod() + // 请求方法: GET, POST 等
				"; URI: " + httpExchange.getRequestURI()); // 请求 URI

				InputStream input = httpExchange.getRequestBody();
				StringBuilder stringBuilder = new StringBuilder();

				new BufferedReader(new InputStreamReader(input)).lines()
						.forEach((String s) -> stringBuilder.append(s + "\n"));

				log.info(stringBuilder.toString());
				input.close();

				// 响应内容
				byte[] respContents = "ok".getBytes("UTF-8");
				// 设置响应头
				httpExchange.getResponseHeaders().add("Content-Type", "text/html; charset=UTF-8");
				// 设置响应code和内容长度
				httpExchange.sendResponseHeaders(200, respContents.length);
				// 设置响应内容
				httpExchange.getResponseBody().write(respContents);
				// 关闭处理器
				httpExchange.close();
			}
		});

		// 创建心跳检测窗口
		httpServer.createContext("/heartbeat", new HttpHandler() {
			@Override
			public void handle(HttpExchange httpExchange) throws IOException {
				// 设置跨域
				addCorsHeader(httpExchange);
				// 心跳包中携带token，将token同步到配置中
				String Authorization = httpExchange.getRequestHeaders().getFirst("Authorization");
				String token = Authorization.replace("Bearer ", "");
				AssistantConfig.properties.setProperty("token", token);
//                log.info("获取token："+token);

				byte[] respContents;

				// 心跳检测返回结果中，未抓取到图片时返回ok，抓取到图像时，返回图像数量。用于提醒有待传图像
				if (imgIdQueue.isEmpty()) {
					respContents = "ok".getBytes("UTF-8");
				} else {
					respContents = String.valueOf(imgIdQueue.size()).getBytes("UTF-8");
				}
				httpExchange.getResponseHeaders().add("Content-Type", "text/html; charset=UTF-8");
				httpExchange.sendResponseHeaders(200, respContents.length);
				httpExchange.getResponseBody().write(respContents);
				httpExchange.close();
			}
		});

		// 创建获取图像ID接口
		httpServer.createContext("/fetchImgIdList", new HttpHandler() {
			@Override
			public void handle(HttpExchange httpExchange) throws IOException {
				// 设置跨域
				addCorsHeader(httpExchange);
				if (httpExchange.getRequestMethod().equalsIgnoreCase("OPTIONS")) {
					httpExchange.getResponseHeaders().add("Content-Type", "text/html; charset=UTF-8");
					httpExchange.sendResponseHeaders(200, 0);
					httpExchange.close();
					return;
				}
				// 获取当前队列中所有已传影像，最大获取4张
				ArrayList<String> img_id_list = new ArrayList<String>(4);
				for (int i = 0; i < 4; ++i) {
					if (!imgIdQueue.isEmpty()) {
						img_id_list.add(imgIdQueue.poll().getImg_id());
					}
				}
				HashMap<String, Object> respObj = new HashMap<String, Object>();
				respObj.put("user_info", new HashMap<String, String>());
				respObj.put("img_id_list", img_id_list);
				JSONObject jsonObj = new JSONObject(respObj);
				byte[] respContents = jsonObj.toString().getBytes("UTF-8");
				httpExchange.getResponseHeaders().add("Content-Type", "application/json;charset=UTF-8");
				httpExchange.sendResponseHeaders(200, respContents.length);
				httpExchange.getResponseBody().write(respContents);
				httpExchange.close();
			}
		});

		// 创建获取检查信息接口
		httpServer.createContext("/getUserInfo", new HttpHandler() {
			@Override
			public void handle(HttpExchange httpExchange) throws IOException {
				// 设置跨域
				addCorsHeader(httpExchange);
				// 获取请求参数
				HashMap<String, String> queryMap = new HashMap<String, String>();
				String queryStr = httpExchange.getRequestURI().getQuery();
				log.info("获取检查信息接口：" + httpExchange.getRequestURI());
				for (String queryItem : queryStr.split("&")) {
					String[] qArr = queryItem.split("=");
					if (qArr.length > 1) {
						queryMap.put(qArr[0], qArr[1]);
					} else {
						queryMap.put(qArr[0], "");
					}
				}

				String id = queryMap.get("id") + "";
				log.info("查询标识record_id:" + queryMap.get("id"));

				// 数据库查询数据
				UserInfo user = RuiKangServiceBySqlServer.selectByBookId(id);
				log.info("user:" + user);
				JSONObject ywJsonObj = new JSONObject();
				List checkItemList = new ArrayList();
				if (user != null) {
					ywJsonObj.put("name", user.getName());
					ywJsonObj.put("gender", user.getGender());
					ywJsonObj.put("birthDate", user.getBirthDate());
					ywJsonObj.put("age", user.getAge());
					ywJsonObj.put("phone",user.getPhone());
					
					String str = AssistantConfig.properties.get("dyjk-report-config") + "";
					checkItemList.add(str);
					
					
					// 根据唯一标识，查询患者信息--start
//					String patientId = ((Map) user.get("data")).get("identityNO") + "";
//					String token = AssistantConfig.properties.getProperty("token");
//					String url = baseUrl + "/patients/findPatientById?patientId=" + patientId;
//					String ret = new TianGaoUtils().get(url, token);
//
//					Map map = new Gson().fromJson(ret, Map.class);
//					log.info("findPatientById "+map);
//					Map content = (Map) map.get("content");
//					List<Map> dataList = (List) content.get("data");
//
//					if (dataList.size() > 0) {
//						for (Map tmpMap : dataList) {
//							Map patientInfoMap = (Map) dataList.get(0);
//							patientInfoMap.put("aiResult", "");
//							
////							FundusPatients p = (FundusPatients) BeanToMapUtil.convertMap(FundusPatients.class, patientInfoMap);
//							FundusPatients p = new FundusPatients();
//							BeanUtils.copyProperties(p, patientInfoMap);;
//							patientList.add(p);
//						}
//					}
					
					List patientList = new ArrayList();
					ywJsonObj.put("patientList", patientList);
				}
				ywJsonObj.put("identifier", id);
				ywJsonObj.put("tmp_save", -1);
				ywJsonObj.put("img_id_list", new ArrayList<String>());
				ywJsonObj.put("check_item_list", checkItemList);
				log.info(ywJsonObj.toString());
				JSONObject respObj = new JSONObject();
				respObj.put("code", 2000);
				respObj.put("content", ywJsonObj);
				String reJsonStr = respObj.toString();
				byte[] respContents = reJsonStr.getBytes("UTF-8");
				httpExchange.getResponseHeaders().add("Content-Type", "application/json;charset=UTF-8");
				httpExchange.sendResponseHeaders(200, respContents.length);
				httpExchange.getResponseBody().write(respContents);
				httpExchange.close();
			}
		});

		// 创建回写报告接口
		httpServer.createContext("/sendReportInfo", new HttpHandler() {
			@Override
			public void handle(HttpExchange httpExchange) throws IOException {
				// 设置跨域
				addCorsHeader(httpExchange);
				byte[] respContents = "ok".getBytes("UTF-8");
				httpExchange.getResponseHeaders().add("Content-Type", "application/json;charset=UTF-8");
				httpExchange.sendResponseHeaders(200, respContents.length);
				httpExchange.getResponseBody().write(respContents);
				httpExchange.close();
			}
		});

	}

	public void setImgIdQueue(ConcurrentLinkedQueue<ImageFileInfoObject> imgIdQueue) {
		this.imgIdQueue = imgIdQueue;
	}

	public void serviceStart() {
		// 启动服务
		httpServer.start();
		log.info("服务启动成功，host：" + AssistantConfig.properties.getProperty("host") + "，port："
				+ AssistantConfig.properties.getProperty("port") + " Version is : 1.1.1");
	}

	public void serviceReStart() {
		// 启动服务
		httpServer.stop(0);
		httpServer.start();
	}

	public void addCorsHeader(HttpExchange httpExchange) throws IOException {
		httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");

		if (httpExchange.getRequestMethod().equalsIgnoreCase("OPTIONS")) {
			httpExchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, OPTIONS");
			httpExchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type,Authorization");
			httpExchange.sendResponseHeaders(204, -1);
		}
	}

	public String doGet(String url, Map<String, String> headers) {
		// 1.获得一个httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 2.生成一个get请求
		HttpGet httpget = new HttpGet(url);
		// 设置header内容
		for (String key : headers.keySet()) {
			httpget.addHeader(key, headers.get(key));
		}

		CloseableHttpResponse response = null;
		try {
			// 3.执行get请求并返回结果
			response = httpclient.execute(httpget);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		String result = null;
		try {
			// 4.处理结果，这里将结果返回为字符串
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public String doPost(String url, Map<String, String> headers) {
		// 1.获得一个httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 2.生成一个post请求
		HttpPost httpPost = new HttpPost(url);
		// 设置header内容
		for (String key : headers.keySet()) {
			httpPost.addHeader(key, headers.get(key));
		}

		CloseableHttpResponse response = null;
		try {
			// 3.执行post请求并返回结果
			response = httpclient.execute(httpPost);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		String result = null;
		try {
			// 4.处理结果，这里将结果返回为字符串
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
}
